package com.tinshow.web.controller.upload;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.tinshow.model.json.JsonResult;
import com.tinshow.model.upload.MyQiNiuPutRet;
import main.java.com.UpYun;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * Created by libo4 on 2017/5/21.
 */
@Controller
@RequestMapping("/file")
public class UploadController {

    private static Configuration cfg = new Configuration(Zone.zone0());

    private static final String accessKey = "tCL43-NG5AAp7uzvvZdLYQGXqK68OsW3FJ5daDhV";
    private static final String secretKey = "lITGXsfZr0w1kUrktdbJc3yhSM8aWinXehSNCdus";
    private static final String bucket = "ranci";

    private static final String upYunBucketName = "tinshow-img";
    private static final String upYunUserName = "leebooe";
    private static final String upYunPassword = "eyen2017@qq.com";

    private static final String imgUrlPath = "https://img.tinshow.com";

    @RequestMapping(value = "upload_file")
    @ResponseBody
    public String uploadImg(@RequestParam("index_image")MultipartFile file){
        if(file.isEmpty()){
            return "文件为空";
        }
        UploadManager uploadManager = new UploadManager(cfg);
        try{
            Auth auth = Auth.create(accessKey,secretKey);
            String upToken = auth.uploadToken(bucket);
            byte[] uploadBytes = file.getBytes();
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(uploadBytes);
            try {
                Response response = uploadManager.put(byteArrayInputStream,null,upToken,null,null);
//                DefaultPutRet ret = new Gson().fromJson(response.bodyString(),DefaultPutRet.class);
                MyQiNiuPutRet putRet = response.jsonToObject(MyQiNiuPutRet.class);
                if(putRet != null && putRet.key != null){
                    String json = "{\"success\":1}";
                    return json;
                }
            }catch(QiniuException ex){
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return "";
    }

    @RequestMapping("upload_file_for_upyun")
    @ResponseBody
    public Object uploadForUpYun(@RequestParam("image_file") MultipartFile file,
            HttpServletRequest request) throws IllegalStateException, IOException{
        UpYun upYun = new UpYun(upYunBucketName,upYunUserName,upYunPassword);
        upYun.setTimeout(60);
        upYun.setApiDomain(UpYun.ED_AUTO);
        String uuid = UUID.randomUUID().toString();
        String filePath = "/imgs/" + uuid;
        System.out.println("https://img.tinshow.com" + filePath);
        try {
            JsonResult jsonResult = null;
            if(file.isEmpty()){
                jsonResult = new JsonResult();
                jsonResult.setSuccess(0);
                jsonResult.setMsg("文件获取异常");
                return jsonResult;
            }else{
                boolean result = upYun.writeFile(filePath,file.getBytes(),true);
                if (result){
                    jsonResult = new JsonResult();
                    jsonResult.setErrno(0);
                    jsonResult.setMsg("文件上传成功");
                    String imgUrl = imgUrlPath + filePath;
                    List<String> imgList = new ArrayList<>();
                    imgList.add(imgUrl);
                    jsonResult.setData(imgList);
                    return jsonResult;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("get_imgs")
    public String getImgs(){
        UpYun upYun = new UpYun(upYunBucketName,upYunUserName,upYunPassword);
        String path = "/imgs/";
        // 获取目录中文件列表
        List<UpYun.FolderItem> items = upYun.readDir(path);
        for (int i = 0; i < items.size(); i++) {
            System.out.println(items.get(i));
        }
        return null;
    }
}
